package com.ljye.jg.ljye.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent;
import com.ljye.jg.ljye.App;
import com.ljye.jg.ljye.R;
import com.ljye.jg.ljye.utils.HttpUtils;
import com.ljye.jg.ljye.utils.Utils;
import com.ljye.jg.ljye.view.MyGridView;

import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//个人风采
public class Activity_Personal_Style extends Activity {
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private final OkHttpClient client = App.client;
    private final MediaType TYPE = MediaType.parse("image/*");
    private ImageView back;//返回
    private MyGridView gridView;
    private TextView bc;
    private String token;
    private LinearLayout ishave;
    private Button submit;
    private GridAdapter gridAdapter;
    private ArrayList<String> imagePaths = new ArrayList<>();
    public View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.back://返回
                    finish();
                    break;
                case R.id.bc://保存
                    up_date();
                    break;


                default:
                    break;
            }
        }
    };
    private int visibility;

    private void up_date() {
        if (imagePaths.size() < 2) {
            Utils.showToast(Activity_Personal_Style.this, "图片太少了哦");
            return;
        }

        new Thread() {
            @Override
            public void run() {
                super.run();
                ArrayList<String> names = new ArrayList<String>();
                ArrayList<File> files = new ArrayList<File>();
                for (int i = 0; i < imagePaths.size() - 1; i++) {
                    String s = imagePaths.get(i);
                    String filename = s.substring(s.lastIndexOf("/") + 1);
                    names.add(i, filename);
                    File file = new File(s);
                    files.add(i, file);
                }
                MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                for (int i = 0; i < names.size(); i++) {
                    if (files.get(i) != null) {
                        String s = names.get(i);
                        File file = files.get(i);
                        Log.d("Activity_up", "-----file" + file);
                        builder.addFormDataPart("pics[]", names.get(i), RequestBody.create(TYPE, files.get(i)));
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Utils.showToast(Activity_Personal_Style.this, "上传失败");
                            }
                        });
                    }
                }
                RequestBody body = builder.build();
                Request request = new Request.Builder()
                        .url(HttpUtils.PATH + "/pics")
                        .addHeader("Accept", HttpUtils.MYAPP)
                        .addHeader("Authorization", "Bearer" + " " + token)
                        .post(body)
                        .build();

                try {
                    Response execute = client.newCall(request).execute();
                    String up_string = execute.body().string();
                    Log.d("Activity_up", up_string);
                    if (execute.isSuccessful()) {
//                                String up_string = execute.body().string();
//                                Log.d("Activity_up", up_string);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Utils.showToast(Activity_Personal_Style.this, "上传成功");
                            }
                        });

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_style);
        initView();
        App application = (App) getApplication();
        token = application.getToken();


        back.setOnClickListener(listener);
        bc.setOnClickListener(listener);


        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setVerticalSpacing(20);//行间距
        gridView.setHorizontalSpacing(20);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PhotoPickerIntent intent = new PhotoPickerIntent(Activity_Personal_Style.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(100); // 最多选择照片数量，默认为6
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult(intent, REQUEST_CAMERA_CODE);
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String imgs = (String) parent.getItemAtPosition(position);
                if ("000000".equals(imgs)) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(Activity_Personal_Style.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(100); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(Activity_Personal_Style.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });

//------------------------------------------------------------
        ArrayList<String> urllist = new ArrayList<>();
//        urllist.add("http://ww3.sinaimg.cn/large/610dc034jw1f5d36vpqyuj20zk0qo7fc.jpg");
//        urllist.add("http://ww3.sinaimg.cn/large/610dc034jw1f5byokn81tj20dw0hiwfe.jpg");
//        urllist.add("http://ww1.sinaimg.cn/large/7a8aed7bjw1f2sm0ns82hj20f00l8tb9.jpg");
//        urllist.add("http://ww3.sinaimg.cn/large/7a8aed7bjw1f2x7vxkj0uj20d10mi42r.jpg");
//        urllist.add("http://ww4.sinaimg.cn/large/7a8aed7bjw1eyaov0c9z4j20iz0sg40t.jpg");
//        urllist.add("http://ww4.sinaimg.cn/large/7a8aed7bjw1exr0p4r0h3j20oy15445o.jpg");
//        urllist.add("http://ww3.sinaimg.cn/large/610dc034jw1f5t889dhpoj20f00mi414.jpg");

        Log.d("Activity_Personal_Aa", "visibility:" + visibility);

        if (urllist.size() > 0) {
            ishave.setVisibility(View.GONE);//如果有照片 就消失
            for (String s : urllist) {//遍历照片集合  全部添加
                imagePaths.add(s);
            }
        }
        visibility = ishave.getVisibility();
        if (visibility == 8) {
            imagePaths.add(0, "000000");
        }
//        ----------------------------------------------
        gridAdapter = new GridAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    ishave.setVisibility(list.size() > 0 ? (View.GONE) : (View.VISIBLE));

                    loadAdpater(list);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    ArrayList<String> ListExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);

                    if (ListExtra.size() > 0) {
                        ishave.setVisibility(View.GONE);
                    }
                    loadAdpater(ListExtra);
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths != null && imagePaths.size() > 0) {
            imagePaths.clear();
        }
        if (paths.contains("000000")) {
            paths.remove("000000");
        }
        paths.add("000000");
        imagePaths.addAll(paths);
        gridAdapter = new GridAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
        try {
            JSONArray obj = new JSONArray(imagePaths);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void initView() {
        back = (ImageView) findViewById(R.id.back);
        gridView = (MyGridView) findViewById(R.id.gridView);
        ishave = (LinearLayout) findViewById(R.id.ishave);
        submit = (Button) findViewById(R.id.submit);


        bc = (TextView) findViewById(R.id.bc);

    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 10) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(Activity_Personal_Style.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            GridAdapter.ViewHolder holder = null;
            if (convertView == null) {
                holder = new GridAdapter.ViewHolder();
                convertView = inflater.inflate(R.layout.item_image, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(holder);
            } else {
                holder = (GridAdapter.ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            if (path.equals("000000")) {
//                if (position > 9) {
//                    holder.image.setVisibility(View.GONE);
//                } else {
                holder.image.setImageResource(R.drawable.add_camera);
//                }
            } else {
                Glide.with(Activity_Personal_Style.this)
                        .load(path)
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }
}

